<template>
  <div v-if="!disabled" class="upload-file">
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :http-request="httpRequestImr"
      :auto-upload="autoUpload"
      :before-upload="beforeUpload"
      :disabled="disabled"
      :drag="drag"
      :limit="props.limit"
      :multiple="props.limit > 1"
      :on-error="excelUploadError"
      :on-exceed="handleExceed"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleFileSuccess"
      :show-file-list="true"
      class="upload-file-uploader"
      name="file"
    >
      <el-button type="primary">
        <Icon icon="ep:upload-filled" />
        {{ t('imrUpload.chooseFile') }}
      </el-button>
      <template v-if="isShowTip" #tip>
        <div class="upload-tips">
          {{
            t('imrUpload.tips', {
              limit: props.limit,
              size: props.fileSize,
              type: props.fileType.join('/')
            })
          }}
        </div>
      </template>
      <template #file="row">
        <div class="flex items-center justify-between pl-[10px] pr-[10px]">
          <span>{{ row.file.name }}</span>
          <div class="flex gap-[10px]">
            <div>
              <el-link
                :href="row.file.url"
                :underline="false"
                download
                target="_blank"
                type="primary"
              >
                {{ t('imrUpload.download') }}
              </el-link>
            </div>
            <div>
              <el-link :underline="false" type="danger" @click="handleRemove(row.file)">
                {{ t('imrUpload.remove') }}
              </el-link>
            </div>
          </div>
        </div>
      </template>
    </el-upload>
  </div>

  <!-- 上传操作禁用时 -->
  <div v-if="disabled" class="upload-file">
    <div
      v-for="(file, index) in fileList"
      :key="index"
      class="flex items-center justify-between pl-[10px] pr-[10px] file-list-item"
    >
      <span>{{ file.name }}</span>
      <div class="ml-10px whitespace-nowrap">
        <el-link :href="file.url" :underline="false" download target="_blank" type="primary">
          {{ t('imrUpload.download') }}
        </el-link>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import type { UploadInstance, UploadProps, UploadRawFile, UploadUserFile } from 'element-plus'
import { UploadFile } from 'element-plus/es/components/upload/src/upload'
import { useI18n } from 'vue-i18n'
import { FileRespVO } from '@/api/infra/file'
import { useUpload } from '@/components/UploadFile/src/useUpload'

defineOptions({ name: 'IMRUpload' })

const message = useMessage() // 消息弹窗
const emit = defineEmits(['update:modelValue'])

const props = defineProps({
  modelValue: {
    type: String,
    default: '[]',
    required: true
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ['doc', 'xls', 'ppt', 'txt', 'pdf']
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 100
  },
  // 数量限制
  limit: {
    type: Number,
    default: 5
  },
  // 自动上传
  autoUpload: {
    type: Boolean,
    default: true
  },
  // 拖拽上传
  drag: {
    type: Boolean,
    default: false
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  // 是否禁用上传组件 ==> 非必传（默认为 false）
  disabled: {
    type: Boolean,
    default: false
  }
})

const { t } = useI18n()

const { httpRequestImr } = useUpload()

// ========== 上传相关 ==========
const uploadRef = ref<UploadInstance>()
const fileList = ref<UploadUserFile[]>([])
const uploadNumber = ref<number>(0)

// v-model传进来的是字符串 内部记录对象数组
const fileVoList = ref<FileRespVO[]>([])

// 文件上传之前判断
const beforeUpload: UploadProps['beforeUpload'] = (file: UploadRawFile) => {
  if (fileList.value.length >= props.limit) {
    message.error(`上传文件数量不能超过${props.limit}个!`)
    return false
  }
  let fileExtension = ''
  if (file.name.lastIndexOf('.') > -1) {
    fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
  }
  const isImg = props.fileType.some((type: string) => {
    if (file.type.indexOf(type) > -1) return true
    return !!(fileExtension && fileExtension.indexOf(type) > -1)
  })
  const isLimit = file.size < props.fileSize * 1024 * 1024
  if (!isImg) {
    message.error(`文件格式不正确, 请上传${props.fileType.join('/')}格式!`)
    return false
  }
  if (!isLimit) {
    message.error(`上传文件大小不能超过${props.fileSize}MB!`)
    return false
  }
  message.success('正在上传文件，请稍候...')
  uploadNumber.value++
}

// 文件上传成功
const handleFileSuccess: UploadProps['onSuccess'] = (res: any): void => {
  fileVoList.value.push(res.data)
  emitUpdateModelValue()
  message.success('上传成功')
}
// 文件数超出提示
const handleExceed: UploadProps['onExceed'] = (): void => {
  message.error(`上传文件数量不能超过${props.limit}个!`)
}
// 上传错误提示
const excelUploadError: UploadProps['onError'] = (): void => {
  message.error('导入数据失败，请您重新上传！')
}
// 删除上传文件
const handleRemove = (file: UploadFile) => {
  const index = fileList.value.map((f) => f.name).indexOf(file.name)
  if (index > -1) {
    fileList.value.splice(index, 1)
    fileVoList.value.splice(index, 1)
    emitUpdateModelValue()
  }
}
const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}

// 监听模型绑定值变动
watch(
  () => props.modelValue,
  (val: string) => {
    if (!val) {
      fileList.value = [] // fix：处理掉缓存，表单重置后上传组件的内容并没有重置
      fileVoList.value = []
      return
    }

    // 反序列化
    fileVoList.value = JSON.parse(val) as FileRespVO[]

    fileList.value = [] // 保障数据为空
    fileList.value.push(...fileVoList.value.map((file) => ({ name: file.name, url: file.url })))
  },
  { immediate: true, deep: true }
)
// 发送文件链接列表更新
const emitUpdateModelValue = () => {
  emit('update:modelValue', JSON.stringify(fileVoList.value))
}
</script>
<style lang="scss" scoped>
.upload-file-uploader {
  .upload-tips {
    font-size: 12px;
    color: #f56c6c;
  }

  :deep(.el-upload-list) {
    margin: 0;
  }

  :deep(.el-upload-list__item) {
    position: relative;
    margin-bottom: 10px;
    line-height: 2;
    border: 1px solid #e4e7ed;
    transition: none;

    &:last-child {
      margin-bottom: 0;
    }
  }

  :deep(.el-upload-list__item-file-name) {
    max-width: 250px;
  }

  :deep(.ele-upload-list__item-content) {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: inherit;
  }

  :deep(.ele-upload-list__item-content-action .el-link) {
    margin-right: 10px;
  }
}

.file-list-item {
  margin-bottom: 10px;
  line-height: 2;
  border: 1px solid #e4e7ed;
  border-radius: 4px;

  &:hover {
    background: rgb(246, 247, 250);
  }

  &:last-child {
    margin-bottom: 0;
  }
}
</style>
